/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.gcit.seniorWish.web.core.intercept;

import com.baomidou.mybatisplus.mapper.Condition;
import com.gcit.seniorWish.core.util.SpringContextHolder;
import com.gcit.seniorWish.web.common.constant.enums.SystemConfigurateEnum;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.dao.RoleMapper;
import com.gcit.seniorWish.web.common.persistence.dao.SystemConfigurateMapper;
import com.gcit.seniorWish.web.common.persistence.model.SystemConfigurate;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import com.gcit.seniorWish.web.modular.system.service.ISystemConfigurateService;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filter that allows access to resources if the accessor is a known user, which
 * is defined as having a known principal. This means that any user who is
 * authenticated or remembered via a 'remember me' feature will be allowed
 * access from this filter.
 * <p/>
 * If the accessor is not a known user, then they will be redirected to the
 * {@link #setLoginUrl(String) loginUrl}
 * </p>
 *
 * @since 0.9
 */
public class PortalUserFilter extends AccessControlFilter {


	/**
	 * Returns <code>true</code> if the request is a
	 * {@link #isLoginRequest(ServletRequest, ServletResponse) loginRequest} or
	 * if the current {@link #getSubject(ServletRequest, ServletResponse)
	 * subject} is not <code>null</code>, <code>false</code> otherwise.
	 *
	 * @return <code>true</code> if the request is a
	 *         {@link #isLoginRequest(ServletRequest, ServletResponse)
	 *         loginRequest} or if the current
	 *         {@link #getSubject(ServletRequest, ServletResponse) subject} is
	 *         not <code>null</code>, <code>false</code> otherwise.
	 */
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (isLoginRequest(request, response)) {
			return true;
		} else {
			Subject subject = getSubject(request, response);
			// If principal is not null, then the user is known and should be
			// allowed access.
			return subject.getPrincipal() != null;
		}
	}

	/**
	 * This default implementation simply calls
	 * {@link #saveRequestAndRedirectToLogin(ServletRequest, ServletResponse)
	 * saveRequestAndRedirectToLogin} and then immediately returns
	 * <code>false</code>, thereby preventing the chain from continuing so the
	 * redirect may execute.
	 */
	@SuppressWarnings("unchecked")
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
		SystemConfigurate configurate = ConstantFactory.me().getSystemConfigurateByKey(SystemConfigurateEnum.SENIOR_WISH_END_DATE.getMessage());
		if (configurate != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH点");
			Date wishEndDate = sdf.parse(configurate.getConfigurateValue()+":00:00");
			// 判断当前时间是否大于截止时间
			if ((new Date().getTime() - wishEndDate.getTime()) > 0) {// 大于不能登录填报系统
				httpServletRequest.setAttribute("message", "本系统于"+sdf1.format(wishEndDate)+"禁止考生登录");
				httpServletRequest.setAttribute("messageFalg", "flag");
				httpServletRequest.getRequestDispatcher("/portal/login.html").forward(request, response);
				return false;
			}
		}
		/**
		 * 如果是ajax请求则不进行跳转
		 */
		if (httpServletRequest.getHeader("x-requested-with") != null
				&& httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
			httpServletResponse.setHeader("sessionstatus", "timeout");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.append("{\"sessionstatus\":\"timeout\"}");
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
			return false;
		} else {

			/**
			 * 第一次点击页面
			 */
			String referer = httpServletRequest.getHeader("Referer");
			if (referer == null) {
				// saveRequestAndRedirectToLogin(request, response);
				httpServletRequest.getRequestDispatcher("/portal/login.html").forward(request, response);
				return false;
			} else {

				/**
				 * 从别的页面跳转过来的
				 */
				if (ShiroKit.getSession().getAttribute("sessionFlag") == null) {
					httpServletRequest.setAttribute("message", "会话超时");
					httpServletRequest.getRequestDispatcher("/portal/login.html").forward(request, response);
					return false;
				} else {
					// saveRequestAndRedirectToLogin(request, response);
					httpServletRequest.getRequestDispatcher("/portal/login.html").forward(request, response);
					return false;
				}
			}
		}
	}
}